(function ($) {
    var timer = null;
    var isNew = false;
    //等待中检定
    var resizeTimer=null;
    var accountDomain = thymeleafData.accountDomain;
    var backUrl = thymeleafData.backUrl;
    var redirect = thymeleafData.redirect;
    var attr = {
        tab_type : location.href.indexOf('#')===-1?'code':location.href.substr(location.href.indexOf('#')+1,location.href.length)
    };
    var docMain = {
        type1_button : $('.J-password-login'),
        type2_button : $('.J-code-login'),
        allContainer : $('.login-type-container'),
        type1_container : $('#J-password-container'),
        type2_container : $('#J-code-container'),
        wechat_login : $('#wechat-login'),
        error_container : $('.login-error-container'),
        redirect : $('#redirect'),
        passwordLogin : $('#passwordLogin'),
        userName : $('#userName'),
        password : $('#passWord'),
        mobile : $('#mobile'),
        getCode : $('#getCode'),
        code : $('#mobile_code'),
        code_login:$('#codeLogin'),
        mobile_error:$('#mobile-error'),
        mobile_tip:$('#mobile-tip'),
        error:$('.login-error'),
        captcha:$('#captcha'),
        captchaCon:$('#captchaCon'),
        captchaParent:$('#captchaParent'),
        mobileCaptcha:$('#mobileCaptcha'),
        mobileCaptchaCon:$('#mobileCaptchaCon'),
        mobileCaptchaParent:$('#mobileCaptchaParent')
    };
    docMain.type1_button.click(showPasswordView);
    docMain.type2_button.click(showCodeView);
    docMain.captchaCon.click(function () {
        reloadCaptcha(this);
    });
    docMain.mobileCaptchaCon.click(function () {
        reloadCaptcha(this);
    });
    function reloadCaptcha(e) {
        var date = new Date().getTime();
        $(e).html('<img width="100px" height="40px" src="/captcha?'+date+'"/>');
        $(e).prev().val(null);
        $(e).prev().focus();
    }
    function init() {
        //判断当前模块，2.5版本无效
        switch (attr.tab_type){
            case 'password':
                showPasswordView();
                break;
            case 'code':
                showCodeView();
                break;
        }
        //验证码初始显示
        if(thymeleafData.needCaptcha){
            docMain.captchaParent.show();
            docMain.mobileCaptchaParent.show();
        }
        if(thymeleafData.userName){
            $('#userName').val(thymeleafData.userName);
        }
        if(thymeleafData.mobile){
            $('#mobile').val(thymeleafData.mobile);
        }
        //判断是否支持placeholder
        var input = document.createElement('input');
        if ('placeholder' in input){
            $('.login-input-tips').hide();
        }else{
            docMain.userName.val('').on('input propertychange',setFocus).on('blur',getFocus);
            docMain.mobile.val('').on('input propertychange',setFocus).on('blur',getFocus);
            docMain.password.val('').on('input propertychange',setFocus).on('blur',getFocus);
            docMain.captcha.val('').on('input propertychange',setFocus).on('blur',getFocus);
            docMain.mobileCaptcha.val('').on('input propertychange',setFocus).on('blur',getFocus);
            docMain.code.val('').on('input propertychange',setFocus).on('blur',getFocus);
        }
    }
    //显示密码登录模块
    function showPasswordView() {
        docMain.type1_button.siblings().removeClass('active');
        docMain.type1_button.addClass('active');
        docMain.error_container.hide();
        docMain.allContainer.hide();
        docMain.type1_container.show();
        attr.tab_type = 'password';
        if(thymeleafData.needCaptcha){
            docMain.captchaParent.show();
            reloadCaptcha(docMain.captchaCon);
        }
    }
    //显示验证码登录模块
    function showCodeView() {
        docMain.type2_button.siblings().removeClass('active');
        docMain.type2_button.addClass('active');
        docMain.error_container.hide();
        docMain.allContainer.hide();
        docMain.type2_container.show();
        attr.tab_type = 'code';
        if(thymeleafData.needCaptcha){
            docMain.mobileCaptchaParent.show();
            reloadCaptcha(docMain.mobileCaptchaCon);
        }
    }

    //微信登录
    docMain.wechat_login.click(function () {
        //appId master wx6dee0381d1c35685
        //appId develop wxb32e19943c0d6201
        var _url = encodeURIComponent(accountDomain+'wechat/callback?redirect='+backUrl);
        var _appid = thymeleafData.appid;
        var _wechat_url = 'https://open.weixin.qq.com/connect/qrconnect?appid='+_appid+
            '&redirect_uri='+_url+
            '&response_type=code&scope=snsapi_login#wechat_redirect';
        window.open(_wechat_url);
    });
    //验证码登录
    docMain.code_login.click(function () {codeLogin();});
    docMain.passwordLogin.click(function () {login();});
    docMain.getCode.click(function () {
        if(resizeTimer){
            clearTimeout(resizeTimer);
        }
        resizeTimer=setTimeout(function() {
            if(isExits(docMain.mobile.val())){
                docMain.error_container.show();
                docMain.mobile_error.hide();
                docMain.mobile_tip.show();
            }else{
                docMain.mobile_tip.hide();
                if(docMain.mobile.val()===''){
                    initError('请输入手机号');
                    return false;
                }else{
                    hideError();
                }
            }
            if(timer===null){
                var captcha = docMain.mobileCaptcha.val().toLowerCase();
                if(thymeleafData.needCaptcha && captcha === ''){
                    initError('请输入字符验证码');
                    return false;
                }
                if(isNew){
                    $.ajax({
                        url:accountDomain+'/mobile/send',
                        data:{mobile:docMain.mobile.val(),type:1,captcha:captcha},
                        success:function (data) {
                            switch (data.result){
                                case true:
                                    countdown(60);
                                    break;
                                case 'needCaptcha':
                                    docMain.mobileCaptchaParent.show();
                                    thymeleafData.needCaptcha = true;
                                    break;
                                default:
                                    reloadCaptcha(docMain.mobileCaptchaCon);
                                    break;
                            }
                            if(data.error){
                                initError(data.error);
                            }
                        },
                        error:function () {
                            initError('未知错误');
                        }
                    });
                }else{
                    $.ajax({
                        url:accountDomain+'/mobile/send',
                        data:{mobile:docMain.mobile.val(),type:101,captcha:captcha},
                        success:function (data) {
                            switch (data.result){
                                case true:
                                    countdown(60);
                                    break;
                                case 'needCaptcha':
                                    docMain.mobileCaptchaParent.show();
                                    thymeleafData.needCaptcha = true;
                                    break;
                                default:
                                    reloadCaptcha(docMain.mobileCaptchaCon);
                                    break;
                            }
                            if(data.error){
                                initError(data.error);
                            }
                        },
                        error:function () {
                            initError('未知错误');
                        }
                    });
                }
            }
        },500);
    });
    $("input").keydown(function(event){
        if (event.which == 13){
            switch (attr.tab_type){
                case 'password':
                    login();
                    break;
                case 'code':
                    codeLogin();
                    break;
            }
        }
    });

    function initError(error) {
        docMain.mobile_tip.hide();
        docMain.error_container.show();
        docMain.mobile_error.show();
        docMain.error.text(error);
    }
    function hideError() {
        docMain.error_container.hide();
        docMain.mobile_error.hide();
        docMain.error.text(null);
    }
    function codeLogin() {
        var mobile = docMain.mobile.val();
        var mobile_code = docMain.code.val();
        var mobileCaptcha = docMain.mobileCaptcha.val();
        var _data = {
            mobile : mobile,
            code : mobile_code,
            redirect:thymeleafData.redirect,
            captcha:mobileCaptcha.toLowerCase()
        };
        if(resizeTimer){
            clearTimeout(resizeTimer);
        }
        resizeTimer=setTimeout(function() {
            if(thymeleafData.needCaptcha && _data.captcha === ''){
                initError('请输入字符验证码');
                return false;
            }
            if(isNew){
                $.ajax({
                    url:accountDomain+'/quick',
                    data:{mobile:_data.mobile,dynamicCode:_data.code,captcha:_data.captcha},
                    type:'post',
                    success:function (data) {
                        if(data.result===true){
                            hideError();
                            parent.location.href = backUrl;
                        }else if(data.result === 'needCaptcha'){
                            docMain.mobileCaptchaParent.show();
                            thymeleafData.needCaptcha = true;
                        }else if(data.error){
                            initError(data.error);
                            reloadCaptcha(docMain.mobileCaptchaCon);
                        }else{
                            initError('创建失败');
                            reloadCaptcha(docMain.mobileCaptchaCon);
                        }
                    },
                    error:function () {
                        initError('未知错误');
                        reloadCaptcha(docMain.mobileCaptchaCon);
                    }
                });
            }else{
                $.ajax({
                    url: accountDomain+'/login/mobile',
                    type: 'post',
                    data: _data,
                    success: function (data) {
                        hideError();
                        if (data.result === true) {
                            parent.location.href = backUrl;
                        }else if(data.result === 'needCaptcha'){
                            docMain.mobileCaptchaParent.show();
                            thymeleafData.needCaptcha = true;
                        } else if (data.error) {
                            initError(data.error);
                            reloadCaptcha(docMain.mobileCaptchaCon);
                        } else {
                            initError('未知错误');
                            reloadCaptcha(docMain.mobileCaptchaCon);
                        }
                    },
                    error: function () {
                        initError('未知错误');
                        reloadCaptcha(docMain.mobileCaptchaCon);
                    }
                });
            }
        },500);
    }
    function isExits(mobile) {
        var _result = null;
        if(mobile===''){
            initError('请输入手机号');
            return false;
        }
        $.ajax({
            url:accountDomain+'/mobile/validate',
            data:{mobile:mobile},
            async:false,
            success:function (data) {
                if(data.result === true){
                    hideError();
                    _result = true;
                }else if(data.error){
                    _result = false;
                }else{
                    _result = false;
                }
            }
        });
        isNew = _result;
        return _result;
    }
    function login() {
        var userName = $("#userName").val();
        var passWord = $("#passWord").val();
        var captcha = $('#captcha').val();
        var _data={
            username:userName,
            password:passWord,
            redirect:thymeleafData.redirect,
            captcha:captcha.toLowerCase()
        };
        if(resizeTimer){
            clearTimeout(resizeTimer);
        }
        resizeTimer=setTimeout(function() {
            if(thymeleafData.needCaptcha && _data.captcha === ''){
                initError('请输入字符验证码');
                return false;
            }
            $.ajax({
                type: "post",
                url: accountDomain+"/login/userName",
                data: _data,
                success: function (data) {
                    hideError();
                    switch (data.result){
                        case true:
                            parent.location.href = backUrl;
                            break;
                        case 'needCaptcha':
                            docMain.captchaParent.show();
                            thymeleafData.needCaptcha = true;
                            break;
                        default:
                            reloadCaptcha(docMain.captchaCon);
                            break;
                    }
                    if(data.error){
                        initError(data.error);
                    }
                },
                error: function () {
                    initError('未知错误');
                    reloadCaptcha(docMain.captchaCon);
                }
            });
        },500);
    }
    //按钮计时器
    function countdown(time) {
        timer = setTimeout(function () {
            countdown(time);
        }, 1000);
        if (time === 0) {
            docMain.getCode.css({'color':'#333333'});
            docMain.getCode.text('重新发送');
            clearTimeout(timer);
            timer = null;
        } else {
            docMain.getCode.css({'color':'#999999'});
            docMain.getCode.text( time+"秒后重新获取");
            time--;
        }
    }
    //输入框事件冒泡
    $(document).delegate('.login-input-container','click',function () {
        var _input = $(this).find('input');
        _input.focus();
    });
    //输入框失去焦点
    function getFocus() {
        var _tip = $(this).parent().find('.login-input-tips');
        if(this.value === ''){
            _tip.show();
        }
    }
    //输入框输入判断
    function setFocus() {
        var _tip = $(this).parent().find('.login-input-tips');
        if (this.value === '') {
            _tip.show();
        } else {
            _tip.hide();
        }
    }
    init();
})(jQuery);